package com.link.base.tencent.corpwx.appchat.service;

import com.alibaba.fastjson.JSONObject;
import com.link.base.tencent.corpwx.agent.service.AgentService;
import com.link.base.tencent.corpwx.appchat.dao.mybatis.mapper.AppChatMapper;
import com.link.base.tencent.corpwx.appchat.dao.mybatis.mapper.AppChatUserMapper;
import com.link.base.tencent.corpwx.appchat.model.AppChat;
import com.link.base.tencent.corpwx.appchat.model.AppChatUser;
import com.link.base.tencent.corpwx.appchat.util.AppChatUtil;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 应用群聊和群聊消息服务
 *
 * @author 欧阳振强
 * @date 2020-01-03 10:37:47.0
 */
@Service
public class AppChatServiceImpl extends BasicServiceImpl<AppChat> implements AppChatService {
    /**群聊状态-等待加入*/
    private static final String CHAT_STATUS_WAIT_ADD = "waitAdd";
    /**群聊状态-已加入*/
    private static final String CHAT_STATUS_ALREADY_ADD = "alreadyAdd";
    /**群聊状态-等待删除*/
    private static final String CHAT_STATUS_WAIT_DEL = "waitDel";
    /**群聊状态-已删除*/
    private static final String CHAT_STATUS_ALREADY_DEL = "alreadyDel";

    @Resource
    private AppChatMapper appChatMapper;
    @Resource
    private AppChatUserMapper appChatUserMapper;
    @Resource
    private AgentService agentService;
    
    @Override
    public BasicMapper<AppChat> getBasicMapper() {
        return appChatMapper;
    }

    @Override
    public void syncAppChatToWx(AppChat record) throws Exception {
        // 获取群聊成员列表
        List<AppChatUser> appChatUserList = appChatUserMapper.listAppChatUserByChatId(record);
        if (appChatUserList == null || appChatUserList.size() <= 0) {
            throw new BasicServiceException("请维护群聊成员！");
        }
        String agentId = record.getAgentId();
        String chatId = record.getChatId();
        if (StringUtils.isBlank(chatId)) {
            // 群聊暂未同步，直接执行创建群聊接口
            List<String> userList = new ArrayList<>();
            for (AppChatUser item: appChatUserList) {
                userList.add(item.getUserId());
            }
            JSONObject resultObj = AppChatUtil.createAppChat(agentService.getExistAccessToken(agentId), record.getChatName(),
                userList, record.getOwner(), record.getChatId());
            // 回写群聊ID
            record.setChatId(resultObj.getString("chatid"));
            appChatMapper.update(record);
            // 更新群聊成员状态
            for (AppChatUser item: appChatUserList) {
                item.setChatStatus(CHAT_STATUS_ALREADY_ADD);
                appChatUserMapper.update(item);
            }
        } else {
            // 群聊已经同步过，需要调用修改群聊接口
            // 待添加群聊成员
            List<String> addUserIdList = new ArrayList<>();
            List<AppChatUser> addUserList = new ArrayList<>();
            // 待删除群聊成员
            List<String> delUserIdList = new ArrayList<>();
            List<AppChatUser> delUserList = new ArrayList<>();
            for (AppChatUser item: appChatUserList) {
                String userId = item.getUserId();
                String chatStatus = item.getChatStatus();
                if (CHAT_STATUS_WAIT_ADD.equals(chatStatus)) {
                    addUserIdList.add(userId);
                    addUserList.add(item);
                } else if (CHAT_STATUS_WAIT_DEL.equals(chatStatus)) {
                    delUserIdList.add(userId);
                    delUserList.add(item);
                }
            }
            // 更新群聊
            AppChatUtil.updateAppChat(agentService.getExistAccessToken(agentId), chatId,
                record.getChatName(), addUserIdList, delUserIdList, record.getOwner());
            // 更新群聊成员状态
            for (AppChatUser item: addUserList) {
                item.setChatStatus(CHAT_STATUS_ALREADY_ADD);
                appChatUserMapper.update(item);
            }
            for (AppChatUser item: delUserList) {
                item.setChatStatus(CHAT_STATUS_ALREADY_DEL);
                appChatUserMapper.update(item);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delAppChatById(AppChat record) throws Exception {
        appChatMapper.deleteById(record);
        appChatUserMapper.delAppChatUserByChatId(record);
    }

    @Override
    public void sendAppChatTextMsg(AppChat record) throws Exception {
        String chatId = record.getChatId();
        if (StringUtils.isBlank(chatId)) {
            throw new BasicServiceException("请先同步群聊，再发送消息！");
        }
        AppChatUtil.sendAppChatText(agentService.getExistAccessToken(record.getAgentId()), record.getChatId(), record.getText());
    }
}